package com.inspector.app.ui.flight.mapsearch.poi

import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.NetworkUtils
import com.example.commen.net.easyHttp.EasyHttpManager
import com.google.gson.JsonElement
import com.huawei.location.lite.common.util.NetworkUtil
import com.inspector.app.BuildConfig
import com.inspector.app.di.location.CustomCoordinateType
import com.inspector.app.ui.flight.mapsearch.MapSearchInstance
import com.inspector.app.util.LogUtil
import com.inspector.app.util.ToastUtil
import com.inspector.app.util.UUIDGenerator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject

/**
 * 天地图关键字搜索
 * 文档地址——http://lbs.tianditu.gov.cn/server/search2.html V2版本搜索可用,V1不可用
 * @author pank. 2023/4/6
 */
class TDMapInstance {

    private val TAG = "TDMapInstance"

    fun getPoiSearch(
        fragment: Fragment,
        keyWord: String,
        listener: (MutableList<MapSearchPoi>?) -> Unit
    ) {
        if (!NetworkUtil.isNetworkAvailable(fragment.requireContext())) {
            ToastUtil.getInstance().showToast("当前搜索类型不支持离线使用")
            listener(null)
            return
        }
        fragment.viewLifecycleOwner.lifecycleScope.launch {
            val jsonElement = withContext(Dispatchers.IO) {
                getPoiSearch(fragment.viewLifecycleOwner, keyWord)
            }
            if (jsonElement?.isJsonNull == true) {
                listener(null)
                return@launch
            }
            listener(swapPoiItems(jsonElement, keyWord))
        }
    }

    //http://lbs.tianditu.gov.cn/server/search2.html [建议调用服务器上的接口]
    private suspend fun getPoiSearch(viewLifecycleOwner: LifecycleOwner, keyWord: String): JsonElement? {
       return withContext(Dispatchers.IO) {
           try {
               val json = JSONObject()
               json.put("keyWord", keyWord)
               json.put("level", "11")
               json.put("mapBound", "73.66,3.86,135.05,53.55")
               json.put("queryType", "1")
               json.put("count", "50")
               json.put("start", "0")
               json.put("show", "1")
               val searchUrl =
                   "http://api.tianditu.gov.cn/v2/search?postStr=$json&type=query&tk=" + BuildConfig.TianDiTuAppKey
               //{"count":"49","resultType":1,"pois":[{"address":"长安街","phone":"010-63095745","poiType":"101","name":"天安门广场","source":"0","hotPointID":"D1B46406399E35A4","lonlat":"116.391358,39.904966"},{"address":"长安街西南方向114米","phone":"","poiType":"101","name":"天安门东站","source":"0","hotPointID":"91822183447EC42A","lonlat":"116.395468,39.906365"},{"address":"景山前街4号故宫博物院","phone":"","poiType":"101","name":"天安门邮政局","source":"0","hotPointID":"5050040626A6AD31","lonlat":"116.391886,39.908024"},{"address":"东长安街天安门城楼","phone":"","poiType":"101","name":"天安门城楼售票处","source":"0","hotPointID":"C04C6083CF5A5A2A","lonlat":"116.390505,39.908403"},{"address":"鲜鱼口街87号","phone":"010-67017790","poiType":"101","name":"北京天安门皇家驿栈","source":"0","hotPointID":"906E0187A6E5D4CF","lonlat":"116.393388,39.895336"},{"address":"长安街天安门广场","phone":"","poiType":"101","name":"天安门广场-国旗","source":"0","hotPointID":"909E618380BAEA3C","lonlat":"116.391288,39.905506"},{"address":"景山前街4号故宫博物院","phone":"","poiType":"101","name":"天安门游客服务中心","source":"0","hotPointID":"104665009F733F0E","lonlat":"116.391886,39.907884"},{"address":"景山前街4号故宫博物院","phone":"","poiType":"101","name":"天安门旅游纪念品","source":"0","hotPointID":"80C2010258581212","lonlat":"116.391906,39.907784"},{"address":"地铁天安门东站西厅","phone":"010-65297629","poiType":"101","name":"天安门东地铁站派出所","source":"0","hotPointID":"418404063B0DD6A7","lonlat":"116.394398,39.905596"},{"address":"东交民巷37号","phone":"010-65241304","poiType":"101","name":"北京市公安局天安门地区分局","source":"0","hotPointID":"50C465879BFF7C0C","lonlat":"116.394468,39.901286"},{"address":"东交民巷44号","phone":"","poiType":"101","name":"天安门旅游商品服务中心","source":"0","hotPointID":"01546087CC6811FD","lonlat":"116.393826,39.900245"},{"address":"北京市东城区","phone":"","poiType":"101","name":"天安门东站A西北口","source":"0","hotPointID":"00746084EA1BD1BD","lonlat":"116.393578,39.906641"},{"address":"北京市东城区","phone":"","poiType":"101","name":"天安门广场东侧2号楼","source":"0","hotPointID":"D1BC248017163AEB","lonlat":"116.394434,39.903222"},{"address":"北京市东城区","phone":"","poiType":"101","name":"天安门东站B东北口","source":"0","hotPointID":"C100240690C50D26","lonlat":"116.396265,39.906706"},{"address":"东交民巷44号","phone":"010-86409660","poiType":"101","name":"北京市人民政府天安门地区管理委员会","source":"0","hotPointID":"40A44504C845A721","lonlat":"116.394238,39.900456"},{"address":"北京市东城区","phone":"","poiType":"101","name":"天安门东站D西南口","source":"0","hotPointID":"8024448006B0881B","lonlat":"116.394407,39.905964"},{"address":"北京市东城区","phone":"","poiType":"101","name":"天安门东站C东南口","source":"0","hotPointID":"81A20183F868B23D","lonlat":"116.395861,39.905927"},{"address":"东交民巷39正南方向132米","phone":"","poiType":"101","name":"北京天安门国际旅行社","source":"0","hotPointID":"50E42583BA742C4A","lonlat":"116.394003,39.901906"},{"address":"前门东大街甲12号","phone":"010-67019208","poiType":"101","name":"99优选酒店天安门广场店","source":"0","hotPointID":"118A21065456CE1A","lonlat":"116.398108,39.898726"},{"address":"西打磨厂街155号","phone":"010-67017762","poiType":"101","name":"怡莱酒店(北京天安门广场店)","source":"0","hotPointID":"01100003148EE5A4","lonlat":"116.398668,39.897536"}],"prompt":[{"type":4,"admins":[{"adminName":"东城区","adminCode":156110101}]}],"status":{"cndesc":"服务正常","infocode":1000},"keyWord":"天安门"}
//            return RetrofitClient.getInstance().getTDMapPoiItems(searchUrl)
               EasyHttpManager.get().getHttpData(viewLifecycleOwner, searchUrl)?.data
           } catch (e: Exception) {
               e.printStackTrace()
               null
           }
       }
    }

    private fun swapPoiItems(
        jsonElement: JsonElement?,
        searchTxt: String
    ): MutableList<MapSearchPoi> {
        val poiItems = mutableListOf<MapSearchPoi>()
        jsonElement?.asJsonObject?.get("pois")?.asJsonArray?.forEach lit@{ item ->
            LogUtil.e(TAG, "item:${item.asJsonObject}")
            val jsonObject = item?.asJsonObject ?: return@lit
            val name = jsonObject.get("name")?.asString
            val lonlat = jsonObject.get("lonlat")?.asString  //116.398668,39.897536
            if (name.isNullOrEmpty() || lonlat.isNullOrEmpty() || !lonlat.contains(",")) return@lit
            val hotPointID = jsonObject.get("hotPointID")?.asString
//            val poiType = jsonObject.get("poiType")?.asString
//            val phone = jsonObject.get("phone")?.asString
//            val address = jsonObject.get("address")?.asString
            try {
                val poiItem = MapSearchPoi()
                poiItem.id =
                    if (hotPointID.isNullOrEmpty()) UUIDGenerator.generate() else hotPointID
                poiItem.name = name
                poiItem.colorSpan = MapSearchInstance.getColorSpan(name, searchTxt)
                poiItem.searchNameWeight = MapSearchInstance.containsSearchWeight(name, searchTxt)
                poiItem.coordType = CustomCoordinateType.GPS
                poiItem.lat = lonlat.split(",".toRegex())[1].toDouble()
                poiItem.lng = lonlat.split(",".toRegex())[0].toDouble()
                poiItems.add(poiItem)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        //[权重排序]
        if(poiItems.isNotEmpty()){
            poiItems.sortByDescending { it.searchNameWeight }
        }
        return poiItems
    }


    companion object {
        val instance: TDMapInstance by lazy { TDMapInstance() }
    }
}